package com.test.common.randcode;

import com.test.common.IdWorker;
import com.test.common.utils.HttpUtil;
import org.apache.commons.io.IOUtils;
import org.openqa.selenium.Cookie;


import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URISyntaxException;
import java.util.Set;

public class GetCodeImage {

    private static String fileName=null;

    public static String downloadImage(String url) {
        try {
            fileName = IdWorker.getIdWorker().nextId()+ ".jpg";
            InputStream inputStream = HttpUtil.getInstance().doGet(url);
            OutputStream outStream = new FileOutputStream("validateCode\\img\\"+fileName);
            IOUtils.copy(inputStream, outStream);
            outStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            return fileName;
        }
    }

    public static InputStream downloadImageToStream(String url) {
        try {
            return HttpUtil.getInstance().doGet(url);
        } catch (URISyntaxException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static InputStream downloadImageToStream(String url,Set<Cookie> cookies) {
        try {
            return HttpUtil.getInstance().doGet(url,cookies,null).getEntity().getContent();
        } catch (URISyntaxException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
